package com.example.easytts.service

import okhttp3.*
import org.json.JSONObject
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit
import okhttp3.MediaType.Companion.toMediaTypeOrNull

@Service
class BaiduTranslateService {
    private val clientId = "YmzWoo47hyzIUp9CidFE8UxL" // 你的 client_id
    private val clientSecret = "1ukDVYiOCCEbUQWJaHFaAGouVAJpmTxs" // 你的 client_secret
    private var accessToken: String? = null
    private val httpClient = OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).build()

    // 获取 access_token
    fun getAccessToken(): String {
        if (accessToken != null) return accessToken!!
        val url = "https://aip.baidubce.com/oauth/2.0/token?client_id=$clientId&client_secret=$clientSecret&grant_type=client_credentials"
        val request = Request.Builder()
            .url(url)
            .post(RequestBody.create("application/json".toMediaTypeOrNull(), ""))
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .build()
        httpClient.newCall(request).execute().use { response ->
            val json = JSONObject(response.body?.string() ?: "")
            accessToken = json.getString("access_token")
            return accessToken!!
        }
    }

    // 调用百度翻译API
    fun translate(q: String, from: String = "auto", to: String = "zh"): String {
        val token = getAccessToken()
        val url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=$token"
        val json = JSONObject()
        json.put("q", q)
        json.put("from", from)
        json.put("to", to)
        val body = RequestBody.create("application/json".toMediaTypeOrNull(), json.toString())
        val request = Request.Builder()
            .url(url)
            .post(body)
            .addHeader("Content-Type", "application/json")
            .build()
        httpClient.newCall(request).execute().use { response ->
            val respJson = JSONObject(response.body?.string() ?: "")
            // 百度返回的结构 result.trans_result 是数组
            val resultObj = respJson.optJSONObject("result")
            val transResult = resultObj?.optJSONArray("trans_result")
            return if (transResult != null && transResult.length() > 0) {
                transResult.getJSONObject(0).optString("dst")
            } else {
                respJson.toString()
            }
        }
    }
} 